package cn.itzzx.lagou;

import cn.itzzx.lagou.datasource.DataSourceHandler;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.StringReader;
import java.util.Properties;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Resource
    private CuratorFramework curatorFramework;

    @Value("${dataSourcePath}")
    private String dataSourcePath;

    @PostConstruct
    public void init() throws Exception {
        Stat stat = curatorFramework.checkExists().forPath(dataSourcePath);
        String dataSourceContent = "jdbc:mysql://10.255.5.29:3306/iot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC,root,iot@002197";
        if (stat == null) {
            //初始化
            curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(dataSourcePath, dataSourceContent.getBytes());
        } else {
            curatorFramework.setData().forPath(dataSourcePath, dataSourceContent.getBytes());
        }
        byte[] bytes = curatorFramework.getData().forPath(dataSourcePath);
        String content = new String(bytes);
        String[] data = content.split(",");
        DataSourceHandler.setConnentInfo(data[0], data[1], data[2]);
    }

    @Bean
    public DataSource dataSource() {
        return DataSourceHandler.getDruidDataSource();
    }

}
